

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=dark>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/my-blog/img/fluid.png">
  <link rel="icon" href="/my-blog/img/fluid.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="木舟">
  <meta name="keywords" content="python Vue Test 测试开发 自动化测试">
  
    <meta name="description" content="协议基础http协议，中文全称：超文本传输协议。 基于tcp&#x2F;ip协议进行构建，每一次与服务器发起http请求，本质上是建立起一个tcp连接。 http属于应用层协议，主要用于传输一些超文本相关的资源文件，比如：html&#x2F;css&#x2F;js&#x2F;img。 HTTP协议永远都是客户端发起请求，服务器回送响应。 并且请求都是有求必应，报错也算是响应的一种，不同的响应类型有不同的 状态码 HTTP协议基于数据是否">
<meta property="og:type" content="article">
<meta property="og:title" content="http协议以及请求工具">
<meta property="og:url" content="https://walker_kwu.gitee.io/my-blog/2022/11/05/notes/js/httpAndTool/">
<meta property="og:site_name" content="My Blog">
<meta property="og:description" content="协议基础http协议，中文全称：超文本传输协议。 基于tcp&#x2F;ip协议进行构建，每一次与服务器发起http请求，本质上是建立起一个tcp连接。 http属于应用层协议，主要用于传输一些超文本相关的资源文件，比如：html&#x2F;css&#x2F;js&#x2F;img。 HTTP协议永远都是客户端发起请求，服务器回送响应。 并且请求都是有求必应，报错也算是响应的一种，不同的响应类型有不同的 状态码 HTTP协议基于数据是否">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2022-11-05T05:09:13.000Z">
<meta property="article:modified_time" content="2023-05-23T10:37:53.257Z">
<meta property="article:author" content="木舟">
<meta property="article:tag" content="测试开发">
<meta property="article:tag" content="测试平台">
<meta property="article:tag" content="javascript">
<meta name="twitter:card" content="summary_large_image">
  
  
    <meta name="referrer" content="no-referrer-when-downgrade">
  
  
  <title>http协议以及请求工具 - My Blog</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/my-blog/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/my-blog/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/my-blog/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"walker_kwu.gitee.io","root":"/my-blog/","version":"1.9.2","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"left","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"follow_dnt":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/my-blog/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/my-blog/js/utils.js" ></script>
  <script  src="/my-blog/js/color-schema.js" ></script>
  


  
<meta name="generator" content="Hexo 6.2.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/my-blog/">
      <strong>木舟</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/my-blog/img/default.png') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="http协议以及请求工具"></span>
          
        </div>

        
          
  <div class="mt-3">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-author" aria-hidden="true"></i>
        木舟
      </span>
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2022-11-05 13:09" pubdate>
          2022年11月5日 下午
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          6.6k 字
        
      </span>
    

    

    
    
      
        <span id="busuanzi_container_page_pv" style="display: none">
          <i class="iconfont icon-eye" aria-hidden="true"></i>
          <span id="busuanzi_value_page_pv"></span> 次
        </span>
        
      
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="padding-left: 2rem; margin-right: -1rem">
    <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">http协议以及请求工具</h1>
            
              <p class="note note-info">
                
                  
                    本文最后更新于：2023年5月23日 晚上
                  
                
              </p>
            
            
              <div class="markdown-body">
                
                <h1 id="协议基础"><a href="#协议基础" class="headerlink" title="协议基础"></a>协议基础</h1><p>http协议，中文全称：超文本传输协议。</p>
<p>基于tcp/ip协议进行构建，每一次与服务器发起http请求，本质上是建立起一个tcp连接。</p>
<p>http属于应用层协议，主要用于传输一些超文本相关的资源文件，比如：html/css/js/img。</p>
<p>HTTP协议永远都是客户端发起请求，服务器回送响应。</p>
<p>并且请求都是有求必应，报错也算是响应的一种，不同的响应类型有不同的 <strong>状态码</strong></p>
<p>HTTP协议基于数据是否加密，主要分两种。</p>
<p>直接构建于TCP协议之上，<strong>没有进行加密传输数据的是HTTP协议</strong>，默认通信<strong>端口是80端口</strong></p>
<p>而构建于TLS或SSL协议之上，<strong>对数据使用SSL加密传输数据的是HTTPS协议</strong>，默认通信<strong>端口是443端口</strong></p>
<p>这个加密针对的是中间传输者，而不是使用者。目的就是为了防止中间传输者进行数据劫持并破译。</p>
<h1 id="请求格式"><a href="#请求格式" class="headerlink" title="请求格式"></a>请求格式</h1><p>对于客户端的<strong>http请求格式</strong>一般分三部分组成，分别是：</p>
<ul>
<li>请求行，协议版本，请求地址，请求方式</li>
<li>请求头，request header</li>
<li>请求体（非必须）</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-comment"># 用python requests库来举例</span><br><span class="hljs-keyword">import</span> requests<br><br><span class="hljs-comment"># 请求行</span><br>url = <span class="hljs-string">&quot;http://www.baidu.com&quot;</span><br><br><span class="hljs-comment"># 请求头</span><br>header = &#123;<br>    <span class="hljs-string">&#x27;content-type&#x27;</span>: <span class="hljs-string">&#x27;application/json&#x27;</span><br>&#125;<br><br><span class="hljs-comment"># 请求体</span><br>data = &#123;<br>    <span class="hljs-string">&#x27;test&#x27;</span>: <span class="hljs-string">&#x27;asd&#x27;</span><br>&#125;<br><br>res = requests.post(url, header, data=data)<br></code></pre></td></tr></table></figure>

<h1 id="响应格式"><a href="#响应格式" class="headerlink" title="响应格式"></a>响应格式</h1><p>包含：</p>
<ul>
<li>响应行，包含：协议版本 状态码 响应文本</li>
<li>响应头，response header</li>
<li>响应体</li>
</ul>
<h1 id="请求方法"><a href="#请求方法" class="headerlink" title="请求方法"></a>请求方法</h1><p>HTTP请求方法（HTTP Request Method），表示客户端希望对服务器指定资源进行哪一种类型的操作，存在多种HTTP请求方法表达增删查改。常见请求方法如下：</p>
<ul>
<li>GET, 表示客户端希望从服务器中<strong>获取</strong>或<strong>下载</strong>资源信息，没有请求体，但有请求参数，参数在url后面，以<code>?</code>隔开。<code>?age=18&amp;name=muzhou</code></li>
<li>POST, 表示客户端希望<strong>上传</strong>文件或通过请求在服务器<strong>创建</strong>资源信息。比如提交表单、上传文件，有请求体。请求体根据格式的不同而不同，比如：form-data，json</li>
<li>put，表示客户端希望<strong>修改或更新</strong>服务器资源, 表示修改全部资源信息，例如数据表的一整个记录</li>
<li>PATCH, 表示客户端希望<strong>修改或更新</strong>服务器资源, 表示修改部分资源信息，例如数据表的一个记录里面某个属性值</li>
<li>DELETE, 示客户端希望<strong>删除或废弃</strong>服务器资源</li>
</ul>
<p>请求方法的区分，其实是一种 <strong>规范</strong>。</p>
<p>比如说GET请求，从规范上来说，是表示请求数据。但是你通过GET请求，也能达到提交数据、新增数据的功能。</p>
<p>目前最常用的请求方式为 <strong>GET、POST</strong>，其中 <strong>POST</strong> 为最最常用，甚至有公司有明确规定：不管什么请求，都采用POST来进行请求。</p>
<h1 id="请求头"><a href="#请求头" class="headerlink" title="请求头"></a>请求头</h1><p>HTTP请求头（Request Header），主要对客户端请求操作进行限制条件与补充说明。常见的标准HTTP请求头如下：</p>
<ul>
<li>Host, 指定客户端请求的服务器的域名和端口号。有些域名本身已经携带接口的指定，如：<a href="http://www.baidu.com（39.156.66.14:443）">www.baidu.com（39.156.66.14:443）</a></li>
<li>Content-Type, 客户端请求携带的请求体数据的媒体类型信息（MIME类型）<ul>
<li>application/json</li>
<li>text/plan</li>
</ul>
</li>
<li>User-Agent, 客户端网络代理程序的版本信息，一般就是浏览器的版本信息。<code>Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36</code></li>
<li>Accept, 客户端能够接收并理解的媒体类型类型（MIME类型），用于表达希望服务端的返回资源格式。类型可以参考 <strong>Content-Type</strong></li>
<li>Connection, 指定本次http通信结束以后，是否关闭TCP网络连接。如果设置持久连接，则可以在一次会话中，可以使用同一个TCP连接，进行多次的HTTP通信，提高效率。<ul>
<li>Connection: keep-alive</li>
<li>Connection: close</li>
</ul>
</li>
<li>Cookie, 一般用来存储token、sessionid等，用于服务端验证身份，以及身份的有效性</li>
</ul>
<h1 id="响应状态码"><a href="#响应状态码" class="headerlink" title="响应状态码"></a>响应状态码</h1><p>状态码（Status Code），用于表达本次服务端在接收客户端请求之后的操作结果的成功或失败结果，由三位整数组成。</p>
<table>
<thead>
<tr>
<th>状态码类型</th>
<th>描述</th>
</tr>
</thead>
<tbody><tr>
<td>1xx</td>
<td>告诉客户端，本次请求，服务端还在持续处理中，并<strong>没有结束</strong>。最少见的状态码。</td>
</tr>
<tr>
<td>2xx</td>
<td>告诉客户端，本次请求，服务端已经接收并<strong>成功受理</strong>了。</td>
</tr>
<tr>
<td>3xx</td>
<td>告诉客户端，服务端位置发生改变，希望客户端<strong>重定向</strong>访问跳转新的服务器地址进行请求</td>
</tr>
<tr>
<td>4xx</td>
<td>告诉<strong>客户端</strong>，本次<strong>请求有误</strong>，服务器无法处理。</td>
</tr>
<tr>
<td>5xx</td>
<td>告诉客户端，本次请求服务端在处理过程中<strong>服务端出错</strong>了。</td>
</tr>
</tbody></table>
<blockquote>
<p>状态码大全：<a target="_blank" rel="noopener" href="https://blog.csdn.net/qq_43040552/article/details/123087163">https://blog.csdn.net/qq_43040552/article/details/123087163</a><br>博客已转载：<a href="https://walker_kwu.gitee.io/my-blog/2022/11/05/notes/js/statusCode/">https://walker_kwu.gitee.io/my-blog/2022/11/05/notes/js/statusCode/</a></p>
</blockquote>
<p>如今的web项目，发起http/https请求时，能见到的状态码已经很少了。</p>
<p>一般后端接收到请求后，进行代码逻辑处理，如果有异常，基本都会进行捕捉，然后返回项目定义的规范的状态码，通过json格式返回</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-punctuation">&#123;</span><br>    <span class="hljs-attr">&quot;msg&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;error msg&quot;</span><span class="hljs-punctuation">,</span><br>    <span class="hljs-attr">&quot;code&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">5500</span><br><span class="hljs-punctuation">&#125;</span><br></code></pre></td></tr></table></figure>

<p>所以我们目前最常见的几种状态码就是：</p>
<ul>
<li>200, 代表请求成功，服务器已经进行正常的处理</li>
<li>302，临时重定向，表示当前请求会交给其他位置来进行响应。</li>
<li>304，自从上次请求后，请求的资源未修改过。比如图标、图片</li>
<li>404，请求资源、接口不存在</li>
<li>403，无权限</li>
<li>500，服务端报错，一般代表代码逻辑出错，无法处理当前请求</li>
<li>502，服务器瘫痪，比如nginx构架部署时，你去访问就会提示这个。</li>
</ul>
<h1 id="响应头"><a href="#响应头" class="headerlink" title="响应头"></a>响应头</h1><ul>
<li>Connection，同 <strong>请求头</strong></li>
<li>Date，消息发送时间</li>
<li>Content-Type</li>
<li>Server，服务器信息</li>
<li>Content-Length，响应数据大小，以字节为单位</li>
<li>Expires，响应数据的过期事件，告诉客户端在这个时间前，可以直接访问缓存副本。-1表示马上过期，客户端不要缓存当前响应数据。</li>
<li>Access-Control-Allow-Origin，指定哪些网站可以跨域资源共享，*号代表所有网站可以跨域资源共享</li>
<li>Access-Control-Allow-Methods，允许哪些方法来访问</li>
<li>Access-Control-Allow-Headers，允许包含哪些请求头。</li>
</ul>
<h1 id="axios"><a href="#axios" class="headerlink" title="axios"></a>axios</h1><p>Axios 是一个基于 promise 网络请求库，作用于node.js 和浏览器中。</p>
<p>axios十分轻量，安全性更高，可以拦截请求和响应。</p>
<p>目前是Vue用来进行接口请求的最好选择。</p>
<blockquote>
<p>中文文档：<a target="_blank" rel="noopener" href="https://www.axios-http.cn/docs/intro">https://www.axios-http.cn/docs/intro</a></p>
</blockquote>
<h2 id="特性"><a href="#特性" class="headerlink" title="特性"></a>特性</h2><ul>
<li>从浏览器创建 XMLHttpRequests</li>
<li>从 node.js 创建 http 请求</li>
<li>支持 Promise API</li>
<li>拦截请求和响应</li>
<li>转换请求和响应数据</li>
<li>取消请求</li>
<li>自动转换JSON数据</li>
<li>客户端支持防御XSRF</li>
<li>支持多请求并发</li>
</ul>
<h2 id="引入使用"><a href="#引入使用" class="headerlink" title="引入使用"></a>引入使用</h2><p>三种方式：</p>
<ul>
<li>通过npm安装，在项目中安装后通过 <strong>import axios from ‘axios’</strong> 使用 <code>npm install axios --save</code> 安装</li>
<li>通过下载到本地的方式使用</li>
<li>通过cdn的方式引入使用</li>
</ul>
<h2 id="基本使用"><a href="#基本使用" class="headerlink" title="基本使用"></a>基本使用</h2><p>这里我使用自己搭建的Django后端服务来进行模拟（需要进行后端跨域）。</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br></pre></td><td class="code"><pre><code class="hljs html"><br><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="language-handlebars"><span class="language-xml"></span></span><br><span class="language-xml"><span class="language-handlebars"></span></span><br><span class="language-xml"><span class="language-handlebars"><span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span></span></span><br><span class="language-xml"><span class="language-handlebars">    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">&quot;https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.js&quot;</span>&gt;</span></span></span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span><br><br>// 创建实例的方式，自由配置实例<br>const myAxios = axios.create(&#123;<br>    baseURL: &#x27;http://127.0.0.1:8000&#x27;,<br>    timeout: 1000,<br>    headers: &#123;&#x27;Content-Type&#x27;: &#x27;application/json&#x27;,&#125;<br>&#125;)<br><br>myAxios.post(&quot;/app/test&quot;, &#123;<br>    flag: 0<br>&#125;).then(res=&gt;&#123;<br>    console.log(res.headers);  // 响应头<br>    console.log(res.data);  // 响应内容<br>    console.log(res.status);  // 响应状态码<br>&#125;)<br><br>// 直接请求<br>axios.post(&quot;/app/test&quot;, <br>&#123;<br>    flag: 0<br>&#125;,<br>&#123;<br>    header: &#123;&#x27;Content-Type&#x27;: &#x27;application/json&#x27;,&#125;,<br>    baseURL: &#x27;http://127.0.0.1:8000&#x27;,<br>&#125;<br>).then(res=&gt;&#123;<br>    console.log(res.headers);  // 响应头<br>    console.log(res.data);  // 响应内容<br>    console.log(res.status);  // 响应状态码<br>&#125;)<br><br>// get<br><br>axios.post(&quot;/app/test&quot;, <br>&#123;<br>    header: &#123;&#x27;Content-Type&#x27;: &#x27;application/json&#x27;,&#125;,<br>    baseURL: &#x27;http://127.0.0.1:8000&#x27;,<br>    // get请求参数params<br>    params: &#123;<br>        flag: 0<br>    &#125;<br>&#125;<br>).then(res=&gt;&#123;<br>    console.log(res.headers);  // 响应头<br>    console.log(res.data);  // 响应内容<br>    console.log(res.status);  // 响应状态码<br>&#125;)<br><br><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span><br></code></pre></td></tr></table></figure>

<h2 id="拦截器"><a href="#拦截器" class="headerlink" title="拦截器"></a>拦截器</h2><p>有时候，我们需要借助拦截器帮我们来实现一些前置、后置操作。</p>
<h3 id="请求拦截器"><a href="#请求拦截器" class="headerlink" title="请求拦截器"></a>请求拦截器</h3><p>比如每次请求前，添加token</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-comment">// 添加请求拦截器</span><br>axios.<span class="hljs-property">interceptors</span>.<span class="hljs-property">request</span>.<span class="hljs-title function_">use</span>(<span class="hljs-keyword">function</span> (<span class="hljs-params">config</span>) &#123;<br>    <span class="hljs-comment">// 在发送请求之前做些什么</span><br>    <span class="hljs-keyword">return</span> config;<br>  &#125;, <span class="hljs-keyword">function</span> (<span class="hljs-params">error</span>) &#123;<br>    <span class="hljs-comment">// 对请求错误做些什么</span><br>    <span class="hljs-keyword">return</span> <span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">reject</span>(error);<br>  &#125;);<br><br></code></pre></td></tr></table></figure>

<h3 id="响应拦截器"><a href="#响应拦截器" class="headerlink" title="响应拦截器"></a>响应拦截器</h3><p>比如每次响应后，判断状态码来显示对应的msg</p>
<p>或者判断状态码是否为403，然后进行token刷新</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs javascript">axios.<span class="hljs-property">interceptors</span>.<span class="hljs-property">response</span>.<span class="hljs-title function_">use</span>(<span class="hljs-keyword">function</span> (<span class="hljs-params">response</span>) &#123;<br>    <span class="hljs-comment">// 对响应数据做点什么</span><br>    <span class="hljs-keyword">return</span> response;<br>  &#125;, <span class="hljs-keyword">function</span> (<span class="hljs-params">error</span>) &#123;<br>    <span class="hljs-comment">// 超出 2xx 范围的状态码都会触发该函数。</span><br>    <span class="hljs-comment">// 对响应错误做点什么</span><br>    <span class="hljs-keyword">return</span> <span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">reject</span>(error);<br>  &#125;);<br></code></pre></td></tr></table></figure>

<h2 id="响应处理"><a href="#响应处理" class="headerlink" title="响应处理"></a>响应处理</h2><p>响应有两种状态，一种是成功，一种是失败。针对响应，有三个函数可以调用，其实对应的就是 <strong>promise</strong></p>
<ul>
<li>then, 响应成功函数</li>
<li>catch，响应失败函数</li>
<li>finally，不管响应如何，都会执行的函数</li>
</ul>
<p>then/catch函数都都是回调函数，都会接收到 <strong>response</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><br>axios.<span class="hljs-title function_">post</span>().<span class="hljs-title function_">then</span>(<span class="hljs-function"><span class="hljs-params">res</span>=&gt;</span>&#123;<br>    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&quot;我成功了&quot;</span>)<br>&#125;).<span class="hljs-title function_">catch</span>(<span class="hljs-function"><span class="hljs-params">res</span>=&gt;</span>&#123;<br>    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&quot;我失败了&quot;</span>)<br>&#125;).<span class="hljs-title function_">finally</span>(<span class="hljs-function">()=&gt;</span>&#123;<br>    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&quot;不管怎么样，我都要执行&quot;</span>)<br>&#125;)<br></code></pre></td></tr></table></figure>

<h2 id="axios与异步编程"><a href="#axios与异步编程" class="headerlink" title="axios与异步编程"></a>axios与异步编程</h2><p>axios天生就支持异步，天生支持promise api。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs javascript">myAxios.<span class="hljs-title function_">post</span>(<span class="hljs-string">&quot;/app/test&quot;</span>, &#123;<br>    <span class="hljs-attr">flag</span>: <span class="hljs-number">0</span><br>&#125;).<span class="hljs-title function_">then</span>(<span class="hljs-function"><span class="hljs-params">res</span>=&gt;</span>&#123;<br>    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&quot;我后执行&quot;</span>);<br>&#125;)<br><br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&quot;我先执行&quot;</span>);<br></code></pre></td></tr></table></figure>

<p>异步编程 <strong>async/await</strong> 的出现，就是为了解决回调地狱的出现。</p>
<p>回调地狱：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-comment">// 后续接口都依赖前一个接口的请求响应</span><br>myAxios.<span class="hljs-title function_">post</span>(<span class="hljs-string">&quot;xxx&quot;</span>).<span class="hljs-title function_">then</span>(<span class="hljs-function"><span class="hljs-params">res</span>=&gt;</span>&#123;<br>    myAxios.<span class="hljs-title function_">post</span>(<span class="hljs-string">&quot;xxx&quot;</span>).<span class="hljs-title function_">then</span>(<span class="hljs-function"><span class="hljs-params">res</span>=&gt;</span>&#123;<br>        myAxios.<span class="hljs-title function_">post</span>(<span class="hljs-string">&quot;xxx&quot;</span>).<span class="hljs-title function_">then</span>(<span class="hljs-function"><span class="hljs-params">res</span>=&gt;</span>&#123;<br>        <br>        &#125;)<br>    &#125;)<br>&#125;)<br></code></pre></td></tr></table></figure>

<p>如今可以写成:</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-keyword">const</span> <span class="hljs-title function_">fn</span> = <span class="hljs-keyword">async</span> (<span class="hljs-params"></span>)=&gt;&#123;<br>    <span class="hljs-keyword">const</span> res1 = <span class="hljs-keyword">await</span> myAxios.<span class="hljs-title function_">post</span>(<span class="hljs-string">&quot;xxx&quot;</span>)<br>    <span class="hljs-keyword">const</span> res2 = <span class="hljs-keyword">await</span> myAxios.<span class="hljs-title function_">post</span>(<span class="hljs-string">&quot;xxx&quot;</span>)<br>    <span class="hljs-keyword">const</span> res3 = <span class="hljs-keyword">await</span> myAxios.<span class="hljs-title function_">post</span>(<span class="hljs-string">&quot;xxx&quot;</span>)<br>&#125;<br></code></pre></td></tr></table></figure>

<p>当然，axios也支持通过promise发起并发请求，因为axios本身返回的就是一个promise对象。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-keyword">const</span> <span class="hljs-title function_">req1</span> = (<span class="hljs-params"></span>)=&gt;&#123;<br>    <span class="hljs-keyword">return</span> myAxios.<span class="hljs-title function_">post</span>(<span class="hljs-string">&quot;/app/test&quot;</span>, &#123;<span class="hljs-attr">flag</span>: <span class="hljs-number">0</span>&#125;)<br>&#125;<br><span class="hljs-keyword">const</span> <span class="hljs-title function_">req2</span> = (<span class="hljs-params"></span>)=&gt;&#123;<br>    <span class="hljs-keyword">return</span> myAxios.<span class="hljs-title function_">post</span>(<span class="hljs-string">&quot;/app/test&quot;</span>, &#123;<span class="hljs-attr">flag</span>: <span class="hljs-number">0</span>&#125;)<br>&#125;<br><span class="hljs-keyword">const</span> <span class="hljs-title function_">req3</span> = (<span class="hljs-params"></span>)=&gt;&#123;<br>    <span class="hljs-keyword">return</span> myAxios.<span class="hljs-title function_">post</span>(<span class="hljs-string">&quot;/app/test&quot;</span>, &#123;<span class="hljs-attr">flag</span>: <span class="hljs-number">0</span>&#125;)<br>&#125;<br><br><span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">all</span>([<br>    <span class="hljs-title function_">req1</span>(),<br>    <span class="hljs-title function_">req2</span>(),<br>    <span class="hljs-title function_">req3</span>(),<br>]).<span class="hljs-title function_">then</span>(<span class="hljs-function"><span class="hljs-params">res</span>=&gt;</span>&#123;<br>    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(res);  <span class="hljs-comment">// [res1, res2, res3]</span><br>&#125;)<br></code></pre></td></tr></table></figure>

<h2 id="简单封装"><a href="#简单封装" class="headerlink" title="简单封装"></a>简单封装</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-keyword">function</span> <span class="hljs-title function_">myPost</span>(<span class="hljs-params">url, requestBody, fn</span>)&#123;<br>    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>)=&gt;</span>&#123;<br>        myAxios.<span class="hljs-title function_">post</span>(url, requestBody)<br>        .<span class="hljs-title function_">then</span>(<span class="hljs-function"><span class="hljs-params">res</span>=&gt;</span>&#123;<br>            <span class="hljs-comment">// 判断响应状态码</span><br>            <span class="hljs-keyword">if</span> (res.<span class="hljs-property">code</span> != <span class="hljs-number">500</span>)&#123;<br>                <span class="hljs-comment">// 当后端状态码为200时, 执行后置回调函数</span><br>                <span class="hljs-keyword">if</span> (res.<span class="hljs-property">data</span>.<span class="hljs-property">code</span> == <span class="hljs-number">100</span>)&#123;<br>                    msg.<span class="hljs-title function_">success</span>(res.<span class="hljs-property">data</span>.<span class="hljs-property">msg</span>)<br>                &#125;<br>                <span class="hljs-title function_">fn</span>(res)<br>                <span class="hljs-title function_">resolve</span>(res)<br>            &#125;<span class="hljs-keyword">else</span>&#123;<br>                <span class="hljs-title function_">reject</span>(res)<br>            &#125;<br>        &#125;).<span class="hljs-title function_">catch</span>(<span class="hljs-function"><span class="hljs-params">res</span>=&gt;</span><span class="hljs-title function_">reject</span>(res))<br>    &#125;)<br>&#125;<br></code></pre></td></tr></table></figure>
                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/my-blog/categories/%E6%B5%8B%E8%AF%95%E5%BC%80%E5%8F%91/" class="category-chain-item">测试开发</a>
  
  
    <span>></span>
    
  <a href="/my-blog/categories/%E6%B5%8B%E8%AF%95%E5%BC%80%E5%8F%91/javascript/" class="category-chain-item">javascript</a>
  
  

  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/my-blog/tags/%E6%B5%8B%E8%AF%95%E5%BC%80%E5%8F%91/">#测试开发</a>
      
        <a href="/my-blog/tags/%E6%B5%8B%E8%AF%95%E5%B9%B3%E5%8F%B0/">#测试平台</a>
      
        <a href="/my-blog/tags/javascript/">#javascript</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>http协议以及请求工具</div>
      <div>https://walker_kwu.gitee.io/my-blog/2022/11/05/notes/js/httpAndTool/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>木舟</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2022年11月5日</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>更新于</div>
          <div>2023年5月23日</div>
        </div>
      
      <div class="license-meta-item">
        <div>许可协议</div>
        <div>
          
            
            
              <a target="_blank" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">
              <span class="hint--top hint--rounded" aria-label="BY - 署名">
                <i class="iconfont icon-by"></i>
              </span>
              </a>
            
              <a target="_blank" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">
              <span class="hint--top hint--rounded" aria-label="NC - 非商业性使用">
                <i class="iconfont icon-nc"></i>
              </span>
              </a>
            
              <a target="_blank" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">
              <span class="hint--top hint--rounded" aria-label="SA - 相同方式共享">
                <i class="iconfont icon-sa"></i>
              </span>
              </a>
            
          
        </div>
      </div>
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/my-blog/2022/11/05/notes/js/statusCode/" title="状态码大全">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">状态码大全</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/my-blog/2022/11/03/notes/js/JQuery/" title="JQuery--老牌王者">
                        <span class="hidden-mobile">JQuery--老牌王者</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <span>By 木舟</span> <i class="iconfont icon-love"></i> 
    </div>
  
  
    <div class="statistics">
  
  

  
    
      <span id="busuanzi_container_site_pv" style="display: none">
        总访问量 
        <span id="busuanzi_value_site_pv"></span>
         次
      </span>
    
    
      <span id="busuanzi_container_site_uv" style="display: none">
        总访客数 
        <span id="busuanzi_value_site_uv"></span>
         人
      </span>
    
    
  
</div>

  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/my-blog/js/events.js" ></script>
<script  src="/my-blog/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/my-blog/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      headingSelector : CONFIG.toc.headingSelector || 'h1,h2,h3,h4,h5,h6',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      collapseDepth   : CONFIG.toc.collapseDepth || 0,
      scrollSmooth    : true,
      headingsOffset  : -boardTop
    });
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.10/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/my-blog/js/local-search.js" ></script>

  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/my-blog/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
